#include "_stdio.h"


_FILE* _fopen(const char* filename,const char* mode)
{
    int flags = 0;


    //确定文件的打开方式
    if(strcmp(mode,"w") == 0)
    {
        flags |= (O_WRONLY | O_CREAT | O_TRUNC);
    }
    else if(strcmp(mode,"r") == 0)
    {   
        flags |= O_RDONLY;
    }
    else if(strcmp(mode,"a") == 0)
    {
        flags |= (O_WRONLY | O_CREAT | O_APPEND);
    }
    else
    {
        //...
    }

    int fd = 0;
    if(flags & O_RDONLY) fd = open(filename,flags);     //只读
    else fd = open(filename,flags,0666);

    if(fd < 0)      //报告错误信息
    {
        char* msg = strerror(errno);
        write(2,msg,strlen(msg));
        return NULL;
    }
    
    _FILE* fp = (_FILE*)malloc(sizeof(_FILE));      //缓冲区
    assert(fp);
    fp->flags=SYNC_LINE;        //默认为行刷新
    fp->fileno=fd;
    fp->cap=SIZE;
    fp->size=0;
    memset(fp->buffer,0,SIZE);
    return fp;
}



void _fclose(_FILE* fp)
{
    _fflush(fp);
    close(fp->fileno);
}


void _fflush(_FILE* fp)
{
    if(fp->size > 0)
    {
        write(fp->fileno,fp->buffer,fp->size);
        fsync(fp->fileno);
        fp->size=0;
    }
}


void _fwrite(const char* ptr,int len,_FILE* fp)
{
    memcpy(fp->buffer+fp->size,ptr,len);
    fp->size += len;

    if(fp->flags & SYNC_LINE)
    {
        if(fp->buffer[fp->size-1] == '\n')
        {
            write(fp->fileno,fp->buffer,fp->size);
            fp->size=0;
        }
    }
}
